package com.quanshu.exchange.support.db;

import com.j256.ormlite.dao.Dao;
import com.quanshu.exchange.support.db.core.DBController;
import com.quanshu.exchange.support.entity.UserEntity;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by jye on 2017/12/15.
 */
public class UserDao implements IDao<UserEntity> {

    private volatile static UserDao instance;

    public static UserDao getInstance() {
        if (instance == null) {
            synchronized (UserDao.class) {
                if (instance == null) {
                    instance = new UserDao();
                }
            }
        }
        return instance;
    }

    private Dao<UserEntity, String> getDao() throws SQLException {
        return DBController.getInstance().getDB().getDao(UserEntity.class);
    }

    @Override
    public void save(UserEntity userEntity) {
        try {
            getDao().createOrUpdate(userEntity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void save(List<UserEntity> list) {
        if (list == null || list.size() < 1) {
            return;
        }
        for (UserEntity userEntity : list) {
            save(userEntity);
        }
    }

    @Override
    public void delete(UserEntity userEntity) {
        try {
            getDao().delete(userEntity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(String primaryKey) {
        try {
            getDao().deleteById(primaryKey);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(UserEntity userEntity) {
        try {
            getDao().update(userEntity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public UserEntity query(String primaryKey) {
        try {
            return getDao().queryForId(primaryKey);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<UserEntity> queryForAll() {
        try {
            return getDao().queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<UserEntity> queryForNoLabel() {
        try {
            return getDao().queryBuilder().where().eq("label_id", "").query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
